﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Store.DateModel;
using System.Web.Security;


namespace FNSShoppingCart
{
    public struct ShoppingCartUpdates
    {
        public int ProductId;
        public int PurchaseQuantity;
        public bool RemoveItem;
    }

    public class MyShoppingCart : System.Web.UI.Page
    {
        public const string CartId = "ShoppingCart_Id";


        public String GetShoppingCartId()
        {
            if (Session[CartId] == null)
            {
                if (System.Web.HttpContext.Current.Request.IsAuthenticated)
                {
                    var user = Membership.GetUser(User.Identity.Name);
                    Session[CartId] = user.ProviderUserKey.ToString();
                }
                else 
                { 
                    Session[CartId] = Guid.NewGuid().ToString(); 
                }
            }
            return Session[CartId].ToString();
        }

        public decimal GetTotal(string cartID)
        {

            using (var db = new StoreDBEntitiesConnection())
            {
                decimal cartTotal = 0;
                try
                {
                    var myCart = (from c in db.ViewCarts where c.CartID == cartID select c);
                    if (myCart.Count() > 0)
                    {
                        cartTotal = myCart.Sum(od => (decimal)od.Quantity * (decimal)od.price);
                    }
                }
                catch (Exception exp)
                {
                    throw new Exception("ERROR: Unable to Calculate Order Total - " + exp.Message.ToString(), exp);
                }
                return (cartTotal);
            }
        }
        public int GetNumberOfProducts(string cartID)
        {

            using (var db = new StoreDBEntitiesConnection())
            {
                int prodnr = 0;
                try
                {
                    var myCart = (from c in db.ViewCarts where c.CartID == cartID select c);
                    prodnr = myCart.Count();
                }
                catch (Exception exp)
                {
                    throw new Exception("ERROR: Unable to get the number of products - " + exp.Message.ToString(), exp);
                }
                return (prodnr);
            }
        }
        public void AddItem(string cartID, int productID, int quantity)
        {
            using (var db = new StoreDBEntitiesConnection())
            {
                try
                {
                    var myItem = (from c in db.ShoppingCarts
                                  where c.CartID == cartID
                                  where c.ProductID == productID
                                  select c).FirstOrDefault();
                    if (myItem == null)
                    {
                        ShoppingCart cartadd = new ShoppingCart();
                        cartadd.CartID = cartID;
                        cartadd.ProductID = productID;
                        cartadd.Quantity = quantity;
                        cartadd.DateCreated = DateTime.Now;
                        db.ShoppingCarts.AddObject(cartadd);
                    }
                    else
                    {
                        myItem.Quantity += quantity;
                    }

                    db.SaveChanges();
                }
                catch (Exception exp)
                {
                    throw new Exception("ERROR: Unable to Add Item to Cart - " + exp.Message.ToString(), exp);
                }
            }

        }

        public void UpdateShoppingCartDatabase(String cartId, ShoppingCartUpdates[] CartItemUpdates)
        {
            using (var db = new StoreDBEntitiesConnection())
            {
                try
                {
                    int CartItemCount = CartItemUpdates.Count();
                    var myCart = (from c in db.ViewCarts where c.CartID == cartId select c);
                    foreach (var cartItem in myCart)
                    {
                        // Iterate through all rows within shopping cart list
                        for (int i = 0; i < CartItemCount; i++)
                        {
                            if (cartItem.ID == CartItemUpdates[i].ProductId)
                            {
                                if (CartItemUpdates[i].PurchaseQuantity < 1 || CartItemUpdates[i].RemoveItem == true)
                                {
                                    RemoveItem(cartId, cartItem.ID);
                                }
                                else
                                {
                                    UpdateItem(cartId, cartItem.ID, CartItemUpdates[i].PurchaseQuantity);
                                }
                            }
                        }
                    }
                }
                catch (Exception exp)
                {
                    throw new Exception("ERROR: Unable to Update Cart Database - " + exp.Message.ToString(), exp);
                }
            }
        }
        public void RemoveItem(string cartID, int productID)
        {
            using (var db = new StoreDBEntitiesConnection())
            {
                try
                {
                    var myItem = (from c in db.ShoppingCarts where c.CartID == cartID && c.ProductID == productID select c).FirstOrDefault();
                    if (myItem != null)
                    {
                        db.DeleteObject(myItem);
                        db.SaveChanges();
                    }

                }
                catch (Exception exp)
                {
                    throw new Exception("ERROR: Unable to Remove Cart Item - " + exp.Message.ToString(), exp);
                }
            }

        }
        public void UpdateItem(string cartID, int productID, int quantity)
        {
            using (var db = new StoreDBEntitiesConnection())
            {
                try
                {
                    var myItem = (from c in db.ShoppingCarts where c.CartID == cartID && c.ProductID == productID select c).FirstOrDefault();
                    if (myItem != null)
                    {
                        myItem.Quantity = quantity;
                        db.SaveChanges();
                    }
                }
                catch (Exception exp)
                {
                    throw new Exception("ERROR: Unable to Update Cart Item - " + exp.Message.ToString(), exp);
                }
            }

        }

        public IList<ViewCart> GetShoppingCartProducts(string cartID)
        {
            IList<ViewCart> query;
            using (var db = new StoreDBEntitiesConnection())
            {
                try
                {
                    query = (db.ViewCarts.Where(p => p.CartID == cartID)).ToList();
                }
                catch (Exception ex)
                {
                    throw new Exception("ERROR:ServiceLayer: Unable to Load ALL Products - " + ex.Message.ToString(), ex);
                }
            }
            return query;
        }

        public int SubmitOrder(string UserName, string tiplivrare, string metodadeplata)
        {
            var livrare_detalii = tiplivrare.Split(',');
            var plata_detalii  = metodadeplata.Split(',');
            int id_comnda = 0;
            using (var db = new StoreDBEntitiesConnection())
            {
                try
                {
                    //------------------------------------------------------------------------+
                    //  Add New Order Record                                                  |
                    //------------------------------------------------------------------------+
                    var user = Membership.GetUser(UserName);
                    Order newOrder = new Order();
                    newOrder.UserID = Guid.Parse(user.ProviderUserKey.ToString());
                    newOrder.created_at = DateTime.Now;
                    newOrder.shiping_date = CalculateShipDate();

                    newOrder.shipping_address = livrare_detalii[0];
                    newOrder.billing_address = livrare_detalii[0];
                    db.Orders.AddObject(newOrder);
                    db.SaveChanges();
                    
                    id_comnda = (from id in db.Orders select id.ID).Max();

                    //------------------------------------------------------------------------+
                    //  Create a new OderDetail Record for each item in the Shopping Cart     |
                    //------------------------------------------------------------------------+
                    String cartId = GetShoppingCartId();
                    var myCart = (from c in db.ViewCarts where c.CartID == cartId select c);
                    foreach (ViewCart item in myCart)
                    {
                        int i = 0;
                        if (i < 1)
                        {
                            Orderd_Products od = new Orderd_Products();
                            od.OrderID = id_comnda;
                            od.ProductID = item.ID;
                            od.quantity = item.Quantity;
                            db.Orderd_Products.AddObject(od);
                            i++;
                        }

                        var myItem = (from c in db.ShoppingCarts 
                                      where c.CartID == item.CartID && c.ProductID == item.ID 
                                      select c).FirstOrDefault();
                        if (myItem != null)
                        {
                            db.DeleteObject(myItem);
                        }
                    }
                    db.SaveChanges();
                }
                catch (Exception exp)
                {
                    throw new Exception("ERROR: Unable to Submit Order - " + exp.Message.ToString(), exp);
                }
                

            }

            return id_comnda;
        }



        DateTime CalculateShipDate()
        {
            DateTime shipDate = DateTime.Now.AddDays(4);
            return (shipDate);
        }


        public void MigrateCart(String oldCartId, String UserID)
        {
            using (var db = new StoreDBEntitiesConnection())
            {
                try
                {
                    var myShoppingCart = from cart in db.ShoppingCarts
                                         where cart.CartID == oldCartId
                                         select cart;

                    foreach (ShoppingCart item in myShoppingCart)
                    {
                        item.CartID = UserID;
                    }
                    db.SaveChanges();
                    Session[CartId] = UserID;
                }
                catch (Exception exp)
                {
                    throw new Exception("ERROR: Unable to Migrate Shopping Cart - " + exp.Message.ToString(), exp);
                }
            }
        }

    }
}